import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { RestService } from '../../app/services/rest.service';
import { Tabs } from "ionic-angular";
import { ReportPage } from '../report/report';
import { DevicePage } from '../device/device';
import { ContactPage } from '../contact/contact';
import { HomePage } from '../home/home';
import { MapPage } from '../map/map';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  @ViewChild('mainTabs') tabs: Tabs;
  tab1Root = HomePage;
  tab2Root = ReportPage;
  tab3Root = DevicePage;
  tab4Root = ContactPage;
  tab5Root = MapPage;
  personId = null;
  personName = null;
  deviceId = null;
  deviceName = null;
  devices = [];
  public person: any;
  public tabsisvis = false;
  constructor(private rest: RestService,
    public navParams: NavParams,
    public navCtrl: NavController) {
    // Navigate from loginPage
    this.rest.viewOnly = JSON.parse(localStorage.getItem("viewOnly"))
    if (navParams.data.personName) {
      this.personName = navParams.data.personName;
    } else {
      // Navigate from ScanPage
      this.personName = localStorage.getItem('personName');
      if (this.personName == null) {
        this.personName = this.rest.getUser().username;
      }
    }

    this.rest.getWithParams('/data/person/search/name', {
      name: this.personName,
      institutionId: this.rest.institutionId
    }).subscribe(resp => {
      this.person = resp['_embedded']['persons'][0];
      this.tabsisvis = true;
    }, message => {
      console.error('Failed to get all persons in: ' + message);
    });
  }

  refreshDevices(deviceId) {
    const deviceTmp = [];
    this.devices.forEach(dvc => {
      if (deviceId != dvc.id) {
        deviceTmp.push(dvc)
      }
    });
    this.devices = deviceTmp;
  }
}
